package com.woniuxy.lab.woniu_lab.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.lab.woniu_lab.exception.AccountException;
import com.woniuxy.lab.woniu_lab.exception.UserException;
import com.woniuxy.lab.woniu_lab.model.Account;
import com.woniuxy.lab.woniu_lab.dao.AccountDao;
import com.woniuxy.lab.woniu_lab.model.User;
import com.woniuxy.lab.woniu_lab.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.lab.woniu_lab.service.UserService;
import com.woniuxy.lab.woniu_lab.util.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

import static com.woniuxy.lab.woniu_lab.exception.WebExceptionCode.*;


/**
 * <p>
 * 账户表 服务实现类
 * </p>
 *
 * @author Silas
 * @since 2023-03-15
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountDao, Account> implements AccountService {

    @Resource
    private UserService userService;

    @Override
    public String accountLogin(String username, String password) {

        Account one = getOne(new QueryWrapper<Account>().eq("username", username).eq("password", password));
        if (one == null) {
            throw new AccountException(ACCOUNT_NOT_EXISTS);
        }
        User user = userService.getOne(new QueryWrapper<User>().eq("id", one.getPersonId()));
        if (user == null){
            throw new UserException(USER_IS_NOT_EXISTS);
        }
        if(!"ENABLE".equals(user.getStatus()) ){
            throw new UserException(USER_IS_DISABLED);
        }

        HashMap<String, Integer> map = new HashMap<>();
        map.put("userId",one.getPersonId());
        String token = JwtUtil.getToken(map, 2);// 设置2天过期
        return token;
    }
}
